package com.ruoyi.controller.wechat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.component.WeChatTokenService;
import com.ruoyi.domain.WechatUser;
import com.ruoyi.mapper.WeChatLoginUser;
import com.ruoyi.pojo.WxMpAuthorizationUrl;
import com.ruoyi.service.IWeChatBaseService;
import com.ruoyi.service.IWechatUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author cj
 */
@Api("微信接口")
@RestController
@RequestMapping("/wechat/base")
public class WeChatBaseController {

    @Autowired
    IWeChatBaseService weChatBaseService;

    @Autowired
    IWechatUserService wechatUserService;

    @Autowired
    WeChatTokenService weChatTokenService;



    /**
     * 前端获取网页认证的链接
     * @param wxMpAuthorizationUrl 参数实体
     * @return 认证授权url
     */
    @PostMapping("/getWebAuthUrl")
    public String getWebAuthUrl(@RequestBody WxMpAuthorizationUrl wxMpAuthorizationUrl) {
        return weChatBaseService.getWebAuthUrl(wxMpAuthorizationUrl);
    }



    /**
     * 微信认证登录，系统中已存在则直接返回。否则入库
     *
     * @param code
     * @return
     */
    @GetMapping("/login/{code}")
    @ApiOperation("login")
    AjaxResult login(@PathVariable String code,HttpServletResponse response) {
        //根据 code 获取 openId
        String openid = weChatBaseService.webLogin(code);
        WechatUser wechatUser = getUserByOpenid(openid);
        response.addHeader("token",weChatTokenService.createToken(new WeChatLoginUser(wechatUser,null)));
        return AjaxResult.success(wechatUser);
    }

    /**
     * 根据 code 获取 openid
     * @param code 微信临时 code
     * @return
     */
    @GetMapping("/getOpenid/{code}")
    @ApiOperation("getOpenid")
    AjaxResult getOpenId(@PathVariable String code) {
        return weChatBaseService.webAuth(code);
    }


    /**
     * 返回前端跳转的首页，并在cookie和请求头同中放入token(包含用户请求)
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/redirect/auth")
    @ApiOperation("回调授权接口")
    void redirectAuth(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String code = request.getParameter("code");
        //根据 code 获取 openId
        String openid = weChatBaseService.webLogin(code);
        WechatUser wechatUser = getUserByOpenid(openid);
        response.addHeader("token",weChatTokenService.createToken(new WeChatLoginUser(wechatUser,null)));
        response.sendRedirect("/mappointment/#/home/" + openid);
    }

    /**
     * 根据 openid 获取用户信息
     * @param openid 当前公众号对应用户的账号
     * @return 返回值
     */
    private WechatUser getUserByOpenid(String openid){
        WechatUser wechatUser = wechatUserService.selectWechatUserById(openid);
        if (wechatUser == null) {
            //查询用户信息并且入库
            JSONObject jsonObject = weChatBaseService.getUserInfo(openid);
            wechatUser = JSON.toJavaObject(jsonObject,WechatUser.class);
            wechatUserService.insertWechatUser(wechatUser);
        }
        return wechatUser;
    }

}
